package ogmios.processes;

import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import java.lang.reflect.*;
import ogmios.core.*;

/**
 * A thread that will write text into a JTextComponent, one line at a time.
 */
public class DefaultTextLineInputThread extends Thread
{

    public Document deposit;
    protected BufferedReader input;
    protected Runnable updater;
    protected String line;

    public DefaultTextLineInputThread(JTextComponent newDeposit, InputStream stream)
    {
        deposit = newDeposit.getDocument();
        input = new BufferedReader(new InputStreamReader(stream));
        updater =
            new Runnable()
        {
            public void run()
            {

                try
                {
                    deposit.insertString(deposit.getLength(), line, null);
                }
                catch (BadLocationException ble)
                {
                }

            }
        };
        setDaemon(true);
    }

    public void run()
    {
        try
        {


            while ((line = input.readLine()) != null)
            {
                try
                {

                    SwingUtilities.invokeAndWait(updater);

                }
                catch (InterruptedException ex)
                {
                    OgmiosUtilities.showErrorBox(null, ex, "Process:Input Error");
                }
                catch (InvocationTargetException e)
                {
                    OgmiosUtilities.showErrorBox(null, e, "Process:Input Error");
                }
            }
            input.close();
        }
        catch (IOException ex)
        {
            OgmiosUtilities.showErrorBox(null, ex, "Process:Input Error");
        }
    }


}

